package xiaoqi.springboot.boot.server.handler;

import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.handler.timeout.ReadTimeoutHandler;
import org.springframework.beans.factory.annotation.Autowired;
import xiaoqi.springboot.boot.codec.InvocationDecoder;
import xiaoqi.springboot.boot.codec.InvocationEncoder;
import xiaoqi.springboot.boot.dispatcher.MessageDispatcher;

import java.util.concurrent.TimeUnit;

public class NettyServerHandlerInitializer extends ChannelInitializer<Channel> {

    /**
     * 心跳超时时间
     */
    private static final Integer READ_TIMEOUT_SECONDS = 3 * 60;

    @Autowired
    private MessageDispatcher messageDispatcher;
    @Autowired
    private NettyServerHandler nettyServerHandler;

    @Override
    protected void initChannel(Channel ch) throws Exception {
        // 获得 Channel 对应 ChannelPipeline
        ChannelPipeline channelPipeline = ch.pipeline();
        // 添加一堆 NettyServerHandler 到 ChannelPipeline 中
        channelPipeline.
                // 空闲检测
                addLast(new ReadTimeoutHandler(READ_TIMEOUT_SECONDS, TimeUnit.SECONDS)).
                // 编码器
                addLast(new InvocationEncoder()).
                // 解码器
                addLast(new InvocationDecoder()).
                // 消息分发
                addLast(messageDispatcher).
                // 服务端处理
                addLast(nettyServerHandler);
    }
}
